<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ page language="java" contentType="text/html;  charset=utf-8"
	pageEncoding="utf-8"%>
<html lang="ko">
	<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    
    <title>Faeple</title>
    
    <link rel="stylesheet" href="/resources/css/font-awesome.css">
    <link rel="stylesheet" href="/resources/css/ionicons.min.css">
    <link rel="stylesheet" href="/resources/iCheck/skins/square/blue.css">
    <style type="text/css">
    	body {
			font-family:"Nanum Barun Gothic","맑은 고딕","Malgun Gothic","Apple SD Gothic Neo","돋움",dotum,Arial,sans-serif;
			line-height:1.428571429;
			color:#333;
			padding: 0;
			margin: 0;
			background-color: #eee;
		}
		.header{height:44px;background-color:#fff;border-bottom:1px solid #ddd;position:fixed;top:0;width:100%;z-index:30;}
		.title{width:100%;text-align:center;font-size:16px;font-weight:normal;}
		.left-btn{position:absolute;left:0;top:0;border:0;background-color:#fff;display:block;z-index:20;width:30px;height:43px;}
		.right-btn{position:absolute;right:6px;top:5px;font-size:14px;border:0;background-color:#fff;display:block;z-index:20;}
		.form-group{ margin-top: 15px; overflow: hidden; }
		.form-control{
			width: 100%;
			border-top: 1px solid #ddd;
			border-bottom: 1px solid #ddd;
			border-left: 0;
			border-right: 0;
			background-color: #fff;
			padding: 14px 0 14px 6px;
			-webkit-appearance:none;
			appearance: none;
			-webkit-box-shadow: none;
			-moz-box-shadow: none;
			box-shadow: none;
			border-radius: 0;
			-webkit-border-radius: 0;
			font-size: 14px;
		}
		.imageUpload{
			width: 100%;
			float: left;
			margin-bottom: 10px;
			margin-top: 15px;
		}
		.imageUpload:after{
			content:"";
			clear:both;
			display:block;
			*zoom:1;
		}
		#imageUploadBtn{
			width: 85px;
			height: 85px;
			float: left;
			border: 1px dotted #ccc;
			position: relative;
			cursor: pointer;
			text-align: center;
			line-height: 90px;
			color: #ccc;
			font-size: 35px;
			overflow: hidden;
			padding: 0;
			background-color: #fff;
		}
		#imageUploadBtn > input{
			position: absolute;
			top: 0;
			right: 0;
			margin: 0;
			opacity: 0;
			-ms-filter: 'alpha(opacity=0)';
			font-size: 300px;
			direction: ltr;
			cursor: pointer;
		}
		#imagePreview > div{
			width: 85px;
			height: 85px;
			float: left;
			border: 1px solid #ccc;
			overflow: hidden;
			margin-right: 6px;
			margin-bottom: 6px;
			padding: 0;
			cursor: move;
			position: relative;
			text-align: center;
		}
		#imagePreview > div > img{
			width: auto;
			height: 85px;
			vertical-align: top;
		}
		#imagePreview > div > i{
			position: absolute;
			right: 4px;
			top: 4px;
			cursor: pointer;
			text-shadow: #444 0 1px 1px;
			color: #fff;
			background-color: rgba(0,0,0,0.5);
			padding: 3px;
			border-radius: 4px;
			
		}
		.select2-offscreen{ display: none; }
		.select2-container{ display: block!important; width: 100%!important; border:0!important;}
		.select2-choices{ border:0!important; box-shadow:none!important; -webkit-box-shadow:none!important;}
		.select2-container-multi.select2-container-active .select2-choices{ box-shadow:none!important; -webkit-box-shadow:none!important; border:0!important; }
		.select2-drop-active{ box-shadow:none!important; -webkit-box-shadow:none!important; border:0!important; }
		.select2-container-multi .select2-choices .select2-search-field input { font-size: 14px; }
		#page{padding-bottom:20px!important;}
		
		.alert{
			width:90%;
			position: fixed;
			z-index: 9999;
			left:5%;
			margin:0;
			top: 10px;
			padding: 15px;
			margin-bottom: 20px;
			border: 1px solid transparent;
			border-radius: 4px;
			-webkit-transform: translateY(-120%);
			-o-transform: translateY(-120%);
			-moz-transform: translateY(-120%);
		    transform: translateY(-120%);
			-webkit-transition:all 0.3s ease-in-out;
			-o-transition:all 0.3s ease-in-out;
			-moz-transition:all 0.3s ease-in-out;
			transition:all 0.3s ease-in-out;
		}
		.alert h4 {
			margin-top: 0;
			color: inherit;
		}
		.alert-dismissable .close {
			position: relative;
			top: -2px;
			right: -21px;
			color: inherit;
		}
		.alert.in{
			-webkit-transform: translateY(0);
			-o-transform: translateY(0);
			-moz-transform: translateY(0);
		    transform: translateY(0);
		}
		.alert-info {
			color: #31708f;
			background-color: #d9edf7;
			border-color: #bce8f1;
		}
		.alert-warning {
			color: #8a6d3b;
			background-color: #fcf8e3;
			border-color: #faebcc;
		}
		.close {
			float: right;
			font-size: 21px;
			font-weight: bold;
			line-height: 1;
			color: #000;
			text-shadow: 0 1px 0 #fff;
			filter: alpha(opacity=20);
			opacity: .2;
		}
		.close:hover,
		.close:focus {
			color: #000;
			text-decoration: none;
			cursor: pointer;
			filter: alpha(opacity=50);
			opacity: .5;
		}
		button.close {
			-webkit-appearance: none;
			padding: 0;
			cursor: pointer;
			background: transparent;
			border: 0;
		}
		.write-message-popup{
			border: 1px solid #BCE8F1;
			background-color: #D9EDF7;
			padding: 6px 4px;
			border-radius: 4px;
			color: #31708f;
			margin-top: 6px;
			position: relative;
			font-size: 13px;	
		}
		.write-message-popup:before {
			position: absolute;
			top: -9px;
			left: 33px;
			display: inline-block;
			border-right: 9px solid transparent;
			border-bottom: 9px solid #BCE8F1;
			border-left: 9px solid transparent;
			content: '';
		}
		.write-message-popup:after {
			position: absolute;
			top: -8px;
			left: 33px;
			display: inline-block;
			border-right: 9px solid transparent;
			border-bottom: 9px solid #D9EDF7;
			border-left: 9px solid transparent;
			content: '';
		}
		#postWriteBtn{
			width: 100%;
			border-color: #145fd7;
			background-color: #4a87ee;
			color: #fff;
			border-top: 1px solid #145fd7;
			border-left: 0;
			border-right: 0;
			border-bottom: 1px solid #145fd7;
			font-size: 15px;
			padding: 14px 0;
			font-size: 18px;
			margin-top: 15px;
		}
		.next_btn{
			width: 100%;
			background-color: #e0e0e0;
			color: #333;
			border-top: 1px solid #c2c2c2;
			border-left: 0;
			border-right: 0;
			border-bottom: 1px solid #c2c2c2;
			font-size: 15px;
			padding: 14px 0;
			font-size: 18px;
			margin-top: 15px;
		}
		
		.spinner {
			height: 18px;
		/* 	left: 50%; */
			margin-left: -9px;
			margin-top: -9px;
		/* 	position: absolute; */
		/* 	top: 50%; */
			width: 18px;
			margin: 0 auto;
			background-image: url();
			background-size: 100%;
			-webkit-animation: spin8 0.8s linear infinite;
			-moz-animation: spin8 0.8s linear infinite;
			-o-animation: spin8 0.8s linear infinite;
			animation: spin8 0.8s linear infinite;
		}
		.spinner.small { height: 18px; width: 18px; }
    </style>
</head>

<body>
<!-- header -->
<div class="header">
	<button onclick="history.back();" class="left-btn" style="color: #017AFC;" id="backBtn"><i class="ion-arrow-left-c" style="font-size:34px;"></i></button>
	<button type="button" class="left-btn" onclick="writeStep('prev');" style="color: #017AFC;display:none;" id="prevBtn"><i class="ion-arrow-left-c" style="font-size:34px;"></i></button>
	<h1 class="title"><spring:message text="글쓰기" code="post.upload.write" /></h1>
</div>
<!-- header -->
<div id="write-step1-form" style="margin-top: 70px;">
	<form id="img-form" method="post" enctype="multipart/form-data" action="/imgUpload">
		<div class="form-group">
			<label><spring:message code="post.upload.photo" text="사진" /></label><span style="font-size: 12px; margin-left: 5px; color: #ccc;">(<span id="uploadImageSize">0</span>/8)</span>
			<div class="imageUpload">
				<div id="imagePreview"></div>			
				<div id="imageUploadBtn" title="<spring:message code="post.upload.image"/>"><i class="icon ion-images"></i><input type="file" id="images" name="images" onchange="imagePreview(this)" accept="image/*" multiple="multiple"></div>
			</div>
			<input type="submit" class="btn btn-success btn-lg btn-block" id="catchImgUploadBtn" style="display: none;" title="<spring:message code="post.upload.btn_image"/>" value="<spring:message code="post.upload.btn_image"/>">
			<div style="clear: both;"></div>
			<div class="write-message-popup" id="write-guide-message1">이미지 아이콘을 클릭해 사진을 추가하세요<br>사진은 최대 8장까지 업로드가 가능합니다</div>
		</div>
	</form>
	<div id="uploadSpinner" class="spinner small" style="display:none;"></div>
	<div style="text-align:right;">
		<button type="button" class="next_btn" style="display:none;" onclick="writeStep('next');" id="writeNextStepBtn">다음</button>
	</div>
</div>
<div id="write-step2-form" style="display:none; margin-top: 44px;">
	<form id="write-form" method="post" action="/postWrite">
		<input type="hidden" class="currentposition" id="image1" name="image1">
		<input type="hidden" class="currentposition" id="image2" name="image2">
		<input type="hidden" class="currentposition" id="image3" name="image3">
		<input type="hidden" class="currentposition" id="image4" name="image4">
		<input type="hidden" class="currentposition" id="image5" name="image5">
		<input type="hidden" class="currentposition" id="image6" name="image6">
		<input type="hidden" class="currentposition" id="image7" name="image7">
		<input type="hidden" class="currentposition" id="image8" name="image8">
		<div class="form-group" style="position: relative;">
			<textarea class="form-control" rows="5" id="inputContent" name="inputContent" style="resize:none;" maxlength="399" placeholder="설명을 입력해 주세요"></textarea>
			<input type="hidden" id="tagUser" name="tagUser" value="">
		</div>
		<div class="write-message-popup" id="write-guide-message3" style="margin-bottom:25px;">#해시태그를 입력하거나, @사용자를 언급해보세요.<br>예) #데일리룩, @faeple</div>
		<input type="hidden" name="selectSeason" id="selectSeason" value="1">
		<input type="hidden" name="pw-age" id="pw-age" value="${userDto.age}">
		<div class="form-group" style="clear: both;">
			<c:if test="${userDto.group_type eq 'user'}">
				<input class="form-control" type="text" id="inputSource" name="inputSource" placeholder="<spring:message code="post.upload.source"/>" maxlength="100">
			</c:if>
			<c:if test="${userDto.group_type eq 'seller'}">
				<input class="form-control" type="text" id="inputSource" name="inputSource" placeholder="<spring:message code="post.upload.buylink"/>" maxlength="100">
			</c:if>
		</div>
		<div class="form-group">
			<label title="<spring:message code="common.women" text="여성" />"><input type="radio" name="gender" id="gender" value="womens"><span class="input-label-text"><spring:message code="common.women" text="여성" /></span></label>
			<label title="<spring:message code="common.men" text="남성" />"><input type="radio" name="gender" id="gender" value="mens"><span class="input-label-text"><spring:message code="common.men" text="남성" /></span></label>
			<select class="form-control" style="margin-top:6px;" id="post-category" name="post-category" title="<spring:message code="common.select"/>">
				<option value="w_clothes"><spring:message code="categoryView.w_clothes" text="여성의류" /></option>
				<option value="w_footwear"><spring:message code="categoryView.w_footwear" text="여성신발" /></option>
				<option value="w_bag"><spring:message code="categoryView.w_bag" text="여성가방" /></option>
				<option value="w_accessory"><spring:message code="categoryView.w_accessory" text="여성악세사리" /></option>
				<option value="w_beauty"><spring:message code="categoryView.w_beauty" text="여성뷰티" /></option>
			</select>
		</div>
		<input type="hidden" value="none" id="inputColor" name="inputColor">
		<input class="form-control" type="hidden" id="inputTag" name="inputTag" tabindex="-1" placeholder="<spring:message code="post.upload.tag_ph"/>">
		<div class="form-group">
			<label title="<spring:message code="post.upload.privacy_all" text="모두" />"><input type="radio" name="radioPrivacy" id="radioPrivacy" value="2" checked="checked"><span class="input-label-text"><spring:message code="post.upload.privacy_all" text="모두" /></span></label>
			<label title="<spring:message code="post.upload.privacy_follower" text="팔로워만" />"><input type="radio" name="radioPrivacy" id="radioPrivacy" value="1"><span class="input-label-text"><spring:message code="post.upload.privacy_follower" text="팔로워만" /></span></label>
			<label title="<spring:message code="post.upload.privacy_me" text="나만보기" />"><input type="radio" name="radioPrivacy" id="radioPrivacy" value="0"><span class="input-label-text"><spring:message code="post.upload.privacy_me" text="나만보기" /></span></label>
		</div>
		<button type="button" class="btn btn-success" onclick="postWrite()" id="postWriteBtn" title="<spring:message code="post.upload.submit"/>"><spring:message code="post.upload.submit"/></button>
	</form>
</div>
<script src="/resources/js/jquery-1.11.0.js"></script>
<script src="/resources/js/jquery-ui-1.10.4.custom.min.js"></script>
<script src="/resources/js/jquery.ui.touch-punch.min.js"></script>
<script src="/resources/js/jquery.autosize.min.js"></script>
<script src="/resources/js/jquery.form.js"></script>
<script type="text/javascript" src="/resources/js/icheck.min.js"></script>
<script type="text/javascript">
	function imagePreview(input){
		var fileList = input.files;
		var imgPreview = $("#imagePreview");
		$("#write-guide-message1").hide();
		try{
			if(fileList.length > 8){
	        	alert("사진을 8개 이하로 올려주세요");
	        	input.value = "";
	        }else{
	        	var uploadSize = 0;
	        	$("input.currentposition").each(function(){
	        		if($(this).val() != ""){
	        			uploadSize++;
	        		}
	        	});
	        	if(uploadSize+fileList.length > 8){
	        		alert("사진을 8개 이하로 올려주세요");
	        	}else{
	        		var imgSize = imgPreview.children("div").size();
	                var bar = $(".progress-bar");
	          		var progressBar = $("#progressBar");
	          		var postWriteBtn = $("#postWriteBtn");
	                $.getScript('/resources/js/jquery.form.js', function(){
	            		$("#img-form").ajaxSubmit({
	            			statusCode: { 
	            				400: function() {
	            					$("#imagePreview").empty();
	            					alertShow("danger","이미지 업로드에 실패했습니다", 2000);
	            				},
	            				500: function() {
	            					$("#imagePreview").empty();
	            					alertShow("danger","이미지 업로드에 실패했습니다.", 2000);
	            				}
	            			},
	            			dataType: "json",
	            			beforeSubmit: function() {
	            				$("#uploadSpinner").show();
	            				postWriteBtn.hide();
	            				var percentVal = '0%';
	            		        bar.width(percentVal);
	            		        progressBar.show();
	            			},
	            			uploadProgress: function(event, position, total, percentComplete) {
	            				var percentVal = percentComplete + '%';
	            		        bar.width(percentVal);
	            		    },
	            			success: function(data) {
	            				for(var i=0;i<data.length;i++){
	            					$("#image"+(imgSize+1)).val(data[i].image);
	            					imgSize++;
	            				}
	            				$("#writeNextStepBtn").show();
	            				$("#write-guide-message2").show();
	            			},
	            			complete: function(){
	            				postWriteBtn.show();
	            				progressBar.hide();
	            				$("#uploadSpinner").hide();
	            			}
	            		});
	        		});
	                
	          		var anyWindow = window.URL || window.webkitURL;
	
	                for(var i = 0; i < fileList.length; i++){
	                	var objectUrl = anyWindow.createObjectURL(fileList[i]);
	                	imgPreview.append("<div data-index='"+(i+1)+"'><img src='" + objectUrl + "' /><i class='fa fa-times' title='삭제' onclick='uploadImgTrash(this)'></i></div>");
	                	//window.URL.revokeObjectURL(fileList[i]);
	                }
	                imgPreview.sortable("refresh");
	                
	                $("#uploadImageSize").html(imgPreview.children("div").size());
	                if(imgPreview.children("div").size() == 8){
	                	$("#imageUploadBtn").hide();
	                }
	                
	        	}
	        }
		}catch(e){
			//$("#postWriteBtn").hide();
			$("#catchImgUploadBtn").show();
		}  
	}
	
	String.prototype.parseTagUser = function() {
		hashpattern = /(@[A-Za-z0-9-_]+)/g;
		return this.match(hashpattern);
	};
	
	function postWrite(){
		if($("#inputColor").val() != "none"){
			postWriteSubmitAjax();
		}else{
			var image = new Image;
			image.src = "resources/upload/post/"+$("#image1").val();
			$.getScript('/resources/js/color-thief.js', function(){
				var colorThief = new ColorThief();
				$(image).on("load", function(){
			        var color = colorThief.getColor(image);
		        	$.getScript('/resources/js/ntc.js', function(){
		        		console.log(color);
		        		var hex = "#"+toHex(color[0])+toHex(color[1])+toHex(color[2]);
		        		console.log(hex);
		        		var colorName = ntc.name(hex);
		            	console.log(colorName[1]);
		            	$("#inputColor").val(colorName[1]);
		            	console.log($("#inputColor").val());
		            	postWriteSubmitAjax();
		        	});
				});
			});
		}
	}

	function postWriteSubmitAjax(){
		var bar = $(".progress-bar");
		var progressBar = $("#progressBar");
		var postWriteBtn = $("#postWriteBtn");
		var tagUser;
		if($("#inputContent").val() == ""){
			alertShow("info","설명을 입력해 주세요", 2000);
			//$("#inputContent").focus();
			return false;
		}else{
			tagUser = $("#inputContent").val().parseTagUser();
			//console.log(tagUser);
			if(tagUser != null) tagUser = tagUser.toString();
			$("#tagUser").val(tagUser);
		}
		if($("#inputContent").val().length > 400){
			alertShow("info","설명이 초과되었습니다", 2000);
			return false;
		}
		
		if($("#image1").val() == ""){
			alertShow("info","사진을 하나라도 업로드 해주세요", 2000);
			return false;
		}
		
		$("#inputTag").val(getHashtagParse());
		$.getScript('/resources/js/jquery.form.js', function(){
			$("#write-form").ajaxSubmit({
				statusCode: { 
					400: function() {
						alertShow("danger","오류가 발생하였습니다", 2000);
					},
					500: function() {
						alertShow("danger","오류가 발생하였습니다", 2000);
					}
				},
				beforeSubmit: function() {
					postWriteBtn.hide();
					var percentVal = '0%';
			        bar.width(percentVal);
			        progressBar.show();
				},
				uploadProgress: function(event, position, total, percentComplete) {
					var percentVal = percentComplete + '%';
			        bar.width(percentVal);
			    },
				success: function(data) {
					var percentVal = '100%';
			        bar.width(percentVal);
					if(data != "role" && data != "tag"){
		    			location.replace("/p/"+data);
					}else if(data == "role"){
						alertShow("danger","로그인이 필요합니다", 2000);
					}else{
						alertShow("danger","사용자 태그가 잘못되었습니다. 사용자 아이디를 확인해 주세요", 2000);
						$("#inputContent").next().css({"border-color":"#a94442","box-shadow":"inset 0 1px 1px rgba(0, 0, 0, .075)"});
					}
				},
				complete: function(){
					postWriteBtn.show();
					progressBar.hide();
				}
			});
		});
	}

	function remainContent(){
		var size = $("#inputContent").val().length;
		if(size > 400){
			alert("내용이 초과되었습니다.");
		}else if(size > 370){
			$("#content-length").css("color","#FF0000");
		}else{
			$("#content-length").css("color","#ccc");
		}
		$("#content-length").html(size);
	}
		
	function uploadImgTrash(obj){
		var imgPreview = $("#imagePreview");
		var index = $(obj).parent().index()+1;
		for(index;index<9;index++){
			if($("#image"+index).next().val() == ""){
				$("#image"+index).val("");
				break;
			}
			$("#image"+index).val($("#image"+index).next().val());
		}
		$(obj).parent().remove();
		imgPreview.sortable("refresh");
		var imgUploadSize = imgPreview.children("div").size();
		$("#uploadImageSize").html(imgUploadSize);
		$("#imageUploadBtn").show();
	}
	
	function alertShow(type, message, dealy){
		var $el = $("<div class='alert alert-"+type+"'><button type='button' onclick='alertHide(this)' class='close'>×</button>"+message+"</div>");
		$("body").append($el);
		if(dealy != null){
			setTimeout(function(){$el.addClass("in");},100);
			setTimeout(function(){$el.removeClass("in");setTimeout(function(){$el.remove();},300);}, dealy);
		}
	}
	function alertHide(el){
		var $el = $(el).parent();
		$el.removeClass("in");
		setTimeout(function(){$el.remove();},300);
	}
	
	
	$(function(){
		//$("#inputContent").autosize();
		
		if("${userDto.gender}" == "male"){
			//$('[data-val="mens"]').children("i").removeClass("icon ion-ios-circle-outline").addClass("icon ion-ios-circle-filled").css("color","#4888F2");
			//$('[data-val="womens"]').children("i").removeClass("icon ion-ios-circle-filled").addClass("icon ion-ios-circle-outline").css("color","#444");
			//$("#gender").val("mens");
			$('input[name=gender][value=mens]').prop('checked', true);
			$("#post-category").children("option").eq(0).html("남성의류").val("m_clothes").next().html("남성신발").val("m_footwear").next().html("남성가방").val("m_bag").next().html("남성악세사리").val("m_accessory").next().html("남성뷰티").val("m_beauty");
		}else{
			$('input[name=gender][value=womens]').prop('checked', true);
			//$("#gender").val("womens");
		}
		$('input[type=radio][name=gender]').change(function(){
			if($(this).val() == "womens"){
				//$(this).children("i").removeClass("icon ion-ios-circle-outline").addClass("icon ion-ios-circle-filled").css("color","#4888F2");
				//$(this).next().children("i").removeClass("icon ion-ios-circle-filled").addClass("icon ion-ios-circle-outline").css("color","#444");
				//$("#gender").val("womens");
				$("#post-category").children("option").eq(0).html("여성의류").val("w_clothes").next().html("여성신발").val("w_footwear").next().html("여성가방").val("w_bag").next().html("여성악세사리").val("w_accessory").next().html("여성뷰티").val("w_beauty");
			}else{
				//$(this).children("i").removeClass("icon ion-ios-circle-outline").addClass("icon ion-ios-circle-filled").css("color","#4888F2");
				//$(this).prev().children("i").removeClass("icon ion-ios-circle-filled").addClass("icon ion-ios-circle-outline").css("color","#444");
				//$("#gender").val("mens");
				$("#post-category").children("option").eq(0).html("남성의류").val("m_clothes").next().html("남성신발").val("m_footwear").next().html("남성가방").val("m_bag").next().html("남성악세사리").val("m_accessory").next().html("남성뷰티").val("m_beauty");
			}
		});
		$("#imagePreview").disableSelection();
		$("#imagePreview").sortable({
			placeholder: "ui-state-highlight",
			revert: true,
			zIndex: 9999,
			start: function(e, ui) {
		        $(this).attr('data-previndex', ui.item.index()+1);
		    },
			update: function(e, ui) {
				var newIndex = ui.item.index()+1;
				var oldIndex = parseInt($(this).attr('data-previndex'));
				$(this).removeAttr('data-previndex');
				
				var temp2 = $("#image"+newIndex).val();
				$("#image"+newIndex).val($("#image"+oldIndex).val());
				
				if(newIndex < oldIndex){
					if(oldIndex-newIndex == 1){
						$("#image"+oldIndex).val(temp2);
					}else{
						var total = oldIndex-newIndex;
						for(var i=0;i<total;i++){
							if(i == total-1){
								$("#image"+(oldIndex-i)).val(temp2);
							}else{
								$("#image"+(oldIndex-i)).val($("#image"+(oldIndex-i)).prev().val());
							}
						}
					}
				}else{
					if(newIndex-oldIndex == 1){
						$("#image"+oldIndex).val(temp2);
					}else{
						var total = newIndex-oldIndex;
						for(var i=0;i<total;i++){
							if(i == total-1){
								$("#image"+(oldIndex+i)).val(temp2);
							}else{
								$("#image"+(oldIndex+i)).val($("#image"+(oldIndex+i)).next().val());
							}
						}
					}
				}
			}
		});
		
		/* $("#colorPicker div").click(function(){
			$("#colorPicker div").each(function(){
				$(this).empty();
			});
			if($(this).data("color") == "white" || $(this).data("color") == "yellow" || $(this).data("color") == "beige"){
				$(this).html("<i class='fa fa-check' style='color:#000; font-size:16px;'></i>");
			}else{
				$(this).html("<i class='fa fa-check' style='color:#fff; font-size:16px;'></i>");
			}
			$("#inputColor").val($(this).data("color"));
		}); */
		
		var imgSize = $("#imagePreview").children("div").size();
        var bar = $(".progress-bar");
    	var progressBar = $("#progressBar");
    	var postWriteBtn = $("#postWriteBtn");
    	var imgPreview = $("#imagePreview");
  		$("#img-form").ajaxForm({
  			statusCode: { 
  				400: function() {
  					alertShow("fail","오류가 발생하였습니다", 2000);
  				},
  				500: function() {
  					alertShow("fail","오류가 발생하였습니다", 2000);
  				}
  			},
  			dataType: "json",
  			beforeSubmit: function() {
  				postWriteBtn.hide();
  				var percentVal = '0%';
  		        bar.width(percentVal);
  		        progressBar.show();
  			},
  			uploadProgress: function(event, position, total, percentComplete) {
  				var percentVal = percentComplete + '%';
  		        bar.width(percentVal);
  		    },
  			success: function(data) {
  				alert(data);
  				for(var i=0;i<data.length;i++){
  					$("#image"+(imgSize+1)).val(data[i].image);
  					imgPreview.append("<div><img src='/resources/upload/post/thumbnail/" + data[i].image + "' /></div>");
  					imgSize++;
  				}
  				imgPreview.sortable("refresh");
	                $("#uploadImageSize").html(imgPreview.children("div").size());
	                if(imgPreview.children("div").size() == 8){
	                	$("#imageUploadBtn").hide();
	                }
  			},
  			complete: function(){
  				postWriteBtn.show();
  				progressBar.hide();
  				$("#catchImgUploadBtn").hide();
  			}
  		});
  		/* $("#inputTag").keydown(function(event){
  			if(event.keyCode == 190 || event.keyCode == 191){
  				return false;
  			}
  		});
  		$("#inputTag").select2({tags:[],tokenSeparators: [",", " "]}); */
  		
  		$('input').iCheck({
			checkboxClass: 'icheckbox_square-blue',
			radioClass: 'iradio_square-blue'
		});
	});
	
	function writeStep(type){
		if(type == "next"){
			$("#write-step1-form").hide();
			$("#write-step2-form").show();
			$("#backBtn").hide();
			$("#prevBtn").show();
		}else{
			$("#write-step1-form").show();
			$("#write-step2-form").hide();
			$("#backBtn").show();
			$("#prevBtn").hide();
		}
	}

	function toHex(n) {
		n = parseInt(n,10);
		if (isNaN(n)) return "00";
		n = Math.max(0,Math.min(n,255));
		return "0123456789ABCDEF".charAt((n-n%16)/16)+ "0123456789ABCDEF".charAt(n%16);
	}
	
	function getHashtagParse(){
		var content = $("#inputContent").val().match(/[#]+[A-Za-z0-9가-힣_]+/g);
		if(content != null){
			var hashtag = [];
			$.each(content, function(i, el){
				if($.inArray(el, hashtag) === -1) hashtag.push(el);
			});
			for(var i=0;i<hashtag.length;i++){
				hashtag[i] = hashtag[i].substr(1);
			}
			return hashtag;
		}else{
			return "";
		}
	}
</script>
</body>
</html>